package org.vergil.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.vergil.config.dataConfig.DynamicDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by vergil on 17-4-5.
 */
@Configuration
@PropertySource("classpath:db.properties")
public class DataBaseConfig {

    @Autowired
    private Environment env;

    @Bean
    public DynamicDataSource dataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("devDataSource", devDataSource());
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(devDataSource());
        return dynamicDataSource;
    }

    @Bean
    public DataSource devDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("db.driver"));
        dataSource.setUrl(env.getProperty("db.url"));
        dataSource.setUsername(env.getProperty("db.username"));
        dataSource.setPassword(env.getProperty("db.password"));
        return dataSource;
    }

    @Bean
    public MySQLMaxValueIncrementer incrementer(){
        MySQLMaxValueIncrementer incrementer = new MySQLMaxValueIncrementer();
        incrementer.setDataSource(dataSource());//使用的数据源
        incrementer.setCacheSize(10);//缓存大小
        incrementer.setColumnName("id");//用于生成主键的列名
        incrementer.setIncrementerName("user");//用于生成主键的表名
        return incrementer;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource());
        return transactionManager;
    }

    @Bean
    public NamedParameterJdbcTemplate namedTemplate(){
        return new NamedParameterJdbcTemplate(dataSource());
    }
}
